import frappe
from frappe.model.document import Document
from frappe import _

@frappe.whitelist(allow_guest=False)
def close_sales_order_lines(sales_order, line_status, close_reason, idx_list):
    '''
    批量关闭销售订单行
    '''
    if isinstance(idx_list, str):
        import json
        idx_list = json.loads(idx_list)

    doc = frappe.get_doc("Sales Order", sales_order)
    user = frappe.get_doc("User", frappe.session.user)

    for item in doc.items:
        if item.idx in idx_list:
            item.custom_line_status = line_status
            item.custom_close_reason = close_reason
            item.custom_close_by = user.full_name
            item.custom_close_date = frappe.utils.now_datetime()

    doc.save(ignore_permissions=True)
    frappe.db.commit()

    # doc.status = "To Bill"
    # doc.delivery_status = "Fully Delivered"
    # doc.save(ignore_permissions=True)  # 保存更改
    # frappe.db.commit()  # 提交更改

    # 检查是否存在行状态为 NORMAL 或 PARTIAL_DELIVERY
    # has_normal_or_partial_delivery = any(
    #     item.custom_line_status in ["NORMAL", "PARTIAL_DELIVERY"] for item in doc.items
    # )

    # # 如果没有 NORMAL 或 PARTIAL_DELIVERY 状态的行，修改销售订单状态为 To Bill
    # if not has_normal_or_partial_delivery:
    #     # 调用标准 API 修改状态
    #     doc.status = "To Bill"
    #     doc.save(ignore_permissions=True)  # 保存更改
    #     frappe.db.commit()  # 提交更改

    return {"status": "success"}